package com.liliudong.pinkyponk.api.admin.controller.sys;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liliudong.pinkyponk.api.admin.security.UserDetailsImpl;
import com.liliudong.pinkyponk.biz.base.BaseController;
import com.liliudong.pinkyponk.biz.sys.convert.SysUserConvert;
import com.liliudong.pinkyponk.biz.sys.entity.SysUser;
import com.liliudong.pinkyponk.biz.sys.request.SysUserRequest;
import com.liliudong.pinkyponk.biz.sys.response.SysUserResponse;
import com.liliudong.pinkyponk.biz.sys.service.SysUserOrgService;
import com.liliudong.pinkyponk.biz.sys.service.SysUserRoleService;
import com.liliudong.pinkyponk.biz.sys.service.SysUserService;
import com.liliudong.pinkyponk.core.validator.Create;
import com.liliudong.pinkyponk.core.validator.Update;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * SysUserController
 *
 * @author liliudong
 * @date 2022-05-26 14:53
 **/
@RestController
@RequestMapping("/v1/sys/user")
public class SysUserController extends
        BaseController<SysUser, SysUserRequest, SysUserResponse, SysUserConvert, SysUserService> {

    private final SysUserRoleService sysUserRoleService;
    private final SysUserOrgService sysUserOrgService;

    public SysUserController(SysUserService sysUserService,
                             SysUserRoleService sysUserRoleService,
                             SysUserOrgService sysUserOrgService) {
        super(SysUserConvert.INSTANCE, sysUserService);
        this.sysUserOrgService = sysUserOrgService;
        this.sysUserRoleService = sysUserRoleService;
    }

    /**
     * me
     *
     * @param userDetails
     * @return
     */
    @GetMapping("/me")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> me(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        SysUser sysUser = userDetails.getSysUser();
        return ok(sysUser);
    }

    /**
     * create
     *
     * @param sysUserRequest
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:user:create')")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> create(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @RequestBody @Validated(Create.class) SysUserRequest sysUserRequest) {
        List<Integer> roleIds = sysUserRequest.getRoleIds();
        List<Integer> orgIds = sysUserRequest.getOrgIds();
        // 保存用户角色关系
        sysUserRoleService.saveBatchByUserId(userDetails.getUserId(), roleIds);
        // 保存用户组织关系
        sysUserOrgService.saveBatchByUserId(userDetails.getUserId(), orgIds);
        SysUser sysUser = reqToEntity(sysUserRequest);
        service.save(sysUser);
        return ok(sysUser);
    }

    /**
     * deleteById
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('sys:user:delete')")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> deleteById(@PathVariable Long id) {
        service.removeById(id);
        return ok();
    }

    /**
     * modify
     *
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('sys:user:modify')")
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> modify(@AuthenticationPrincipal UserDetailsImpl userDetails,
                                    @RequestBody @Validated(Update.class) SysUserRequest request) {
        List<Integer> roleIds = request.getRoleIds();
        List<Integer> orgIds = request.getOrgIds();
        // 保存用户角色关系
        sysUserRoleService.saveBatchByUserId(userDetails.getUserId(), roleIds);
        // 保存用户组织关系
        sysUserOrgService.saveBatchByUserId(userDetails.getUserId(), orgIds);
        SysUser sysUser = reqToEntity(request);
        service.updateById(sysUser);
        return ok(sysUser);
    }

    /**
     * list
     *
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public ResponseEntity<?> list(@RequestParam Long current, @RequestParam Long size) {
        Page<SysUser> pageQuery = getPageQuery(current, size);
        Page<SysUser> page = service.page(pageQuery);
        return ok(page);
    }
}
